package com.situ.gym.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.situ.gym.mapper.CoachCourseMapper;
import com.situ.gym.pojo.Course;
import com.situ.gym.pojo.vo.CourseExcelVO;
import org.springframework.beans.BeanUtils;

/**
 * 教练课程Excel导入监听器
 * 用于处理教练课程Excel导入时的数据转换和保存
 *
 * @author ${author}
 * @since 2025-01-27
 */
public class CoachCourseExcelListener extends AnalysisEventListener<CourseExcelVO> {
    
    private final CoachCourseMapper coachCourseMapper;
    private final Long coachId;

    public CoachCourseExcelListener(CoachCourseMapper coachCourseMapper, Long coachId) {
        this.coachCourseMapper = coachCourseMapper;
        this.coachId = coachId;
    }

    @Override
    public void invoke(CourseExcelVO courseExcelVO, AnalysisContext context) {
        System.out.println("CoachCourseExcelListener.invoke - 第" + context.getCurrentRowNum() + "行");
        
        try {
            // 数据验证
            if (courseExcelVO.getName() == null || courseExcelVO.getName().trim().isEmpty()) {
                throw new RuntimeException("第 " + context.getCurrentRowNum() + " 行课程名称不能为空");
            }
            
            // 转换为Course对象
            Course course = new Course();
            BeanUtils.copyProperties(courseExcelVO, course);
            
            // 设置教练ID
            course.setCoachId(coachId);
            
            // 插入的数据避免和原有ID重复
            course.setId(null);
            
            // 保存到数据库
            coachCourseMapper.insert(course);
            
            System.out.println("第 " + context.getCurrentRowNum() + " 行课程 '" + course.getName() + "' 导入成功");
            
        } catch (Exception e) {
            System.err.println("第 " + context.getCurrentRowNum() + " 行数据导入失败: " + e.getMessage());
            throw new RuntimeException("第 " + context.getCurrentRowNum() + " 行数据导入失败: " + e.getMessage(), e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("CoachCourseExcelListener.doAfterAllAnalysed - 共处理" + context.getCurrentRowNum() + "行数据");
        System.out.println("教练课程Excel导入完成");
    }
}
